//
//  TakeIDPhotoViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/14.
//

import UIKit
import RxSwift
import RxCocoa
import AVFoundation
struct UploadIDCardModel: Codable {
    struct CardInfoModel: Codable {
        let frost: String
        var scarred: String
        let openly: String
    }
    let siege: [CardInfoModel]
}

class TakeIDPhotoViewController: UIViewController {

    var product_id = ""
    
    private let bag = DisposeBag()
    
    var naviTitle: String = ""
    
    @IBOutlet weak var naviBar: NavigationBar!
    
    @IBOutlet weak var cardImageView: UIImageView!
    
    let image = BehaviorRelay<UIImage?>.init(value: nil)
    
    let cardInfo = PublishSubject<UploadIDCardModel>()
    
    private var beginDate: Date?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
    }
    
    private func configView() {
        self.naviBar.title = self.naviTitle
        self.naviBar.backClicked.subscribe(onNext: { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        })
        .disposed(by: self.bag)
        self.image
            .map { image in
                if (image != nil) {
                    return image!
                } else {
                    return UIImage(named: "loan_id_idcard")!
                }
            }
            .observe(on: MainScheduler.instance)
            .bind(to: self.cardImageView.rx.image)
            .disposed(by: self.bag)
        self.image
            .filter({$0 != nil})
            .subscribe(onNext: self.uploadImage(image:))
            .disposed(by: self.bag)
        self.cardInfo
            .subscribe(on: MainScheduler.instance)
            .subscribe(onNext: { [weak self] card in
                let confirmVC = IDInformationConfirmController()
                confirmVC.product_id = self!.product_id
                confirmVC.cardModels = card.siege
                confirmVC.doneNotifier.subscribe(onNext: { done in
                    UploadStasticManager.default.uploadRiskPoint(type: 2, beginTime: self?.beginDate)
                    self?.navigationController?.popViewController(animated: true)
                })
                .disposed(by: self!.bag)
                self?.alert(viewController: confirmVC)
            })
            .disposed(by: self.bag)
    }
    
    private func uploadImage(image: UIImage?) {
        guard image != nil else {
            return
        }
        Task {
            do {
                self.showLoading(text: nil)
                let data = image!.jpegData(compressionQuality: 0.5)!
                let res = try await HTTPManager.default.upload(path: Api.uploadIDCard, data: data, fileKey: "whopper", param: ["cordially": 11, "railings": 1], dataType: UploadIDCardModel.self)
                self.hideLoading()
                if res.code == 0 {
                    self.cardInfo.onNext(res.data!)
                } else {
                    self.show(toast: res.state)
                }
            } catch {
                print(error)
                self.hideLoading()
            }
        }
    }
    
    @IBAction func takePhotoAction(_ sender: UIButton) {
        let cameraAuthorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
        switch cameraAuthorizationStatus {
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { grant in
                if grant {
                    DispatchQueue.main.async {
                        let imagePicker = UIImagePickerController()
                        #if DEBUG
                        if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
                            imagePicker.sourceType = .photoLibrary
                        }
                        #else
                        if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
                            imagePicker.sourceType = .camera
                        }
                        imagePicker.cameraDevice = .rear
                        #endif
                        imagePicker.delegate = self
                        imagePicker.modalPresentationStyle = .overFullScreen
                        self.present(imagePicker, animated: true)
                        if self.beginDate == nil {
                            self.beginDate = Date()
                        }
                    }
                } else {
                    DispatchQueue.main.async {
                        let privacyVC = PrivacyEnableViewController()
                        self.alert(viewController: privacyVC)
                    }
                }
            }
            break
        case .authorized:
            DispatchQueue.main.async {
                let imagePicker = UIImagePickerController()
#if DEBUG
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
    imagePicker.sourceType = .photoLibrary
}
#else
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
    imagePicker.sourceType = .camera
}
imagePicker.cameraDevice = .rear
#endif
                imagePicker.delegate = self
                imagePicker.modalPresentationStyle = .overFullScreen
                self.present(imagePicker, animated: true)
                if self.beginDate == nil {
                    self.beginDate = Date()
                }
            }
            break
        default:
            DispatchQueue.main.async {
                let privacyVC = PrivacyEnableViewController()
                self.alert(viewController: privacyVC)
            }
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension TakeIDPhotoViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info[.originalImage] as? UIImage
        self.image.accept(image)
        picker.dismiss(animated: true)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}
